/** 复制文字 */
export const coptText = async (text: string, message = "已经成功复制到剪切板!") => {
  /** clipboard api */
  if (navigator.clipboard) {
    try {
      await navigator.clipboard.writeText(text);
      return message && window.$message.success(message);
    } catch (error: any) {
      window.$message.error("复制失败!" + error?.message);
      return error;
    }
  }
  /** execCommand */
  if (Reflect.has(document, "execCommand")) {
    return new Promise<void>((resolve, reject) => {
      try {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        textArea.setAttribute("readonly", "readonly");
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand("copy");
        document.body.removeChild(textArea);
        message && window.$message.success(message);
        resolve();
      } catch (error: any) {
        window.$message.success("复制失败" + error.message);
        reject(error);
      }
    });
  }

  return Promise.reject("navigator.clipboard 或 document.execCommand 中存在错误或浏览器不支持, 拷贝失败!");
};
